package com.tuanzi.loan.web.bean.system.workflow;

import java.util.Date;

import javax.faces.bean.ApplicationScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tuanzi.loan.workflow.service.WorkflowManagerService;
import com.tuanzi.loan.workflow.service.WorkflowProcessorService;

/**
 * @author Ray 2017/09/22
 */
@Component
@ApplicationScoped
public class WorkflowImageBean {

	private static final long serialVersionUID = -2152778554108785342L;

	@Autowired
	private WorkflowManagerService workflowManagerService;
	@Autowired
	private WorkflowProcessorService workflowProcessorService;

	public StreamedContent getWorkflowImage() throws Exception {
		FacesContext context = FacesContext.getCurrentInstance();

		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			String deploymentId = context.getExternalContext().getRequestParameterMap().get("deploymentId");
			if (StringUtils.isBlank(deploymentId)) {
				return null;
			}
			return new DefaultStreamedContent(workflowManagerService.getDeploymentImage(deploymentId), "image/png", "workflow-process-image-" + new Date());
		}
	}

	public StreamedContent getWorkflowTrackingImage() throws Exception {
		FacesContext context = FacesContext.getCurrentInstance();

		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			String procInstId = context.getExternalContext().getRequestParameterMap().get("procInstId");
			if (StringUtils.isBlank(procInstId)) {
				return null;
			}
			return new DefaultStreamedContent(workflowProcessorService.findProcessTrackingImageByProcInstId(procInstId), "image/png", "workflow-tracking-" + new Date());
		}
	}
}
